<template>
	<!-- 新建工资审批流 -->
	<view class="container"
		style="width: 100%;box-sizing: border-box;background-color: #fff;padding:20rpx 20rpx 20rpx 20rpx">
		<uni-forms ref="form" :modelValue="entity" label-width="100px">
			<view>
				<!-- CompanyId -->
				<uni-forms-item label="所属公司" :rules="$rules.handle.CompanyName" required name="CompanyName">
					<view @click="CustomerChoice('CompanyName')">
						<uni-easyinput v-model="entity.CompanyName" placeholder="请选择所属公司" suffixIcon="compose"
							:disabled="disabled" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="年月" :rules="$rules.handle.iYearMonth" required name="iYearMonth">
					<picker mode="date" fields="month" :value="entity.iYearMonth" @change="bindDateChange">
						<uni-easyinput v-model="entity.iYearMonth" placeholder="请选择年月" :disabled="disabled" />
					</picker>
				</uni-forms-item>
				<uni-forms-item v-if="disabled" label="总金额" name="SalaryAmount">
					<view>
						<uni-easyinput v-model="entity.SalaryAmount" placeholder="总金额" :disabled="disabled" />
					</view>
				</uni-forms-item>

				<uni-forms-item label="备注">
					<view>
						<uni-easyinput v-model="entity.Remark" placeholder="备注" type="textarea" maxlength="300"
							:disabled="disabled" />
					</view>
				</uni-forms-item>
				<!-- 暂时不删除 -->
				<!-- <view style="background-color: #fff;padding:0 20rpx;">
					<uni-forms-item label="附件" name="FilePath">
						<UploadCopy ref="UploadCopy" :action="$action" @onSuccess="onSuccess" :file="FilePath"
							@handlerRemove="handlerRemove" :deletable="disabled">
						</UploadCopy>
					</uni-forms-item>
				</view> -->
			</view>
			<view v-if="title !=='查看'" class="submitButton">
				<u-button v-if="(options.ActivityName ==='开始' && options.State ==4) ||  title ==='新增'" type="primary"
					@click="onSubmit(1)" :loading="loading">提交</u-button>
				<u-button v-else type="primary" @click="onSubmit(2)" :loading="loading">审批</u-button>
			</view>
		</uni-forms>

		<!-- 审批弹窗 -->
		<uni-popup ref="inputDialog" type="dialog">
			<!-- 后续使用该样式直接打开即可 position: absolute;right: 20rpx;top: 20rpx; color="#909390"-->
			<view style="display: flex;justify-content: flex-end;margin-bottom: 10rpx;">
				<uni-icons type="closeempty" size="30" @click="$refs.inputDialog.close()"></uni-icons>
			</view>
			<uni-popup-dialog cancelText="不同意" confirmText="同意" title="审批意见" type="info" :value="comment"
				@close="dialogInputHandleSubmit(false, '审批中')" @confirm="dialogInputHandleSubmit(true, '审批中')"
				before-close>
				<uni-easyinput type="textarea" v-model="comment" placeholder="请输入审批意见" :adjust-position="false" />
			</uni-popup-dialog>
		</uni-popup>

		<!-- 选择日期 -->
		<u-calendar v-model="isCalendar" :mode="mode" placeholder="请选择日期" @change="timeChangeClick"></u-calendar>
		<!-- 引用公司子组件 -->
		<Company ref="Company" @change="changeHandler" @cancel="$refs.Company.close()" :title="'请选择公司'"></Company>
	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	// 引用公司选择子组件
	import Company from '@/components/Company.vue'
	import UploadCopy from "../../components/uploadCopy.vue"
	// 引入公共头部组件
	import {
		//获取公司列表数据
		CompanyDataList,
		// 获取部门下拉列表
		DepartmentList,
		// 新建工资审批
		Salary_PayrollWageApprovalProcess,
		// 获取工资审批流详情
		Salary_ApprovalFormGetTheData,
		// 工资审批提交
		Ai_WorkitemSalaryApproved
	} from "@/api/interface.js";
	export default {
		components: {
			// 公司组件
			Company,
			// 上传子组件
			UploadCopy

		},
		data() {
			return {
				// 审批意见
				comment: '',
				// 禁用
				disabled: false,
				// /附件
				FilePath: [],
				// 加载
				loading: false,
				entity: {},
				// 是否显示日期弹窗
				isCalendar: false,
				// 日期选择
				mode: 'date',
				// 是否展示公司选择底部弹窗组件
				showPopup: false,
				// 底部弹窗列表数据
				columns: [],
				// 点击弹出底部弹窗的字段类型
				dataType: "",
				date: this.getCurrentMonth(),
				ApprovalFormId: "",
				title: ""
			}
		},
		computed: {
			...mapState(["UserInfo", "BillTypeOptions", "ExpenseTypeOptions", "InvoiceClassificationOptions",
				"CompayListOptions"
			]),
		},

		onLoad(options) {
			this.options = options
			this.title = options.title
			this.ApprovalFormId = options.ApprovalFormId
			console.log('工资审批传递过来options------------', this.options)
			if (options.disabled === 'true') {
				this.disabled = true
				uni.setNavigationBarTitle({
					title: '工资审批流详情'
				})
			}
			if (options.ApprovalFormId) {
				// 获取工资审批流详情
				this.getSalary_ApprovalFormGetTheData(options.ApprovalFormId)
			}
		},
		methods: {
			// 年月选择器只显示年月
			getCurrentMonth() {
				const date = new Date()
				let year = date.getFullYear()
				let month = date.getMonth() + 1
				month = month > 9 ? month : '0' + month
				return `${year}-${month}`
			},
			// 年月选择器
			bindDateChange: function(e) {
				// 年月格式化
				this.$set(this.entity, 'iYearMonth', e.target.value.split('-').join(''))
			},
			// 求和函数
			sumObjects(arr, key) {
				return arr.reduce((sum, current) => sum + parseFloat(current[key] || 0), 0)
			},
			// 日期时间选择
			timeClick(type) {
				if (this.disabled) return
				this.isCalendar = true
			},
			// 日期选择calendarChange
			timeChangeClick(event) {
				let iYearMonthArr = event.result.split('-')
				let year = iYearMonthArr[0]
				let month = iYearMonthArr[1]
				// *************注意  存储必须用set赋值  否则校验不通过   ************************************
				this.$set(this.entity, 'iYearMonth', year + month)
				console.log('日期选择', event, iYearMonthArr, this.entity)
				// *************注意  存储必须用set赋值  否则校验不通过   ************************************

			},

			// 上传成功
			onSuccess(fileData, fileEntity, index) {
				var that = this
				let File = []
				let SDRDTOList = []
				console.log('上传成功了----------------------获取过来的', fileData, fileEntity, index)
				// 	if (file.length > 0) {
				// 		let newFile = file
				// 		newFile.forEach(item => {
				// 			File.push(item.url)
				// 			let obj = {
				// 				FileURL: item.url
				// 			}
				// 			SDRDTOList.push(obj)
				// 		})

				// 		this.entity.SDRDTOList = SDRDTOList
				// 		this.entity.File = File
				// 	}
				// 	console.log('上传传过来了', File, SDRDTOList, this.uploadFile, this.entity)
			},
			// 移除附件
			handlerRemove(list, index) {
				console.log('移除附件', list, index)
				// if (this.entity.File && this.entity.File.length > 0) {
				// 	this.entity.File.splice(index, 1)
				// }
				// if (this.entity.SDRDTOList && this.entity.SDRDTOList.length > 0) {
				// 	this.entity.SDRDTOList.splice(index, 1)
				// }
			},

			// 获取工资审批流详情
			getSalary_ApprovalFormGetTheData(id) {
				uni.showLoading({
					title: '加载中'
				})
				Salary_ApprovalFormGetTheData({
					id: id
				}).then(resJson => {
					if (resJson.Success) {
						console.log('获取工资审批流详情', resJson.Data, this.CompayListOptions)
						this.entity = resJson.Data
						// 公司名称回显
						this.entity.CompanyName = this.CompayListOptions.filter(v => v.value === this.entity
							.OrgId)[0] ? this.CompayListOptions.filter(v => v.value ===
							this.entity.OrgId)[0].text : ""
						uni.hideLoading()
					}
				})
			},

			// 底部弹窗选中事件
			changeHandler(children) {
				// 公司和部门名称id赋值
				// 重新选择公司名称  初始化部门名称和id
				this.$set(this.entity, "CompanyName", children.label);
				this.$set(this.entity, "OrgId", children.value);

				this.$forceUpdate()
				// 隐藏底部弹窗
				this.$refs.Company.close()
				console.log('选中了', this.entity)
			},

			// 公司选择
			CustomerChoice(value) { // 获取公司下拉列表数据
				if (this.disabled) return
				this.dataType = ""
				this.dataType = value
				console.log('公司还是部门', value, this.entity)
				// 判断公司名称是否为空  再点击部门选择的时候
				if (value === 'DeptName') {
					if (!this.entity.CompanyName) {
						// 如果没有公司先禁用部门名称
						this.disabledDeptName = true
						this.$errorToast('请先选择公司')
						return
					}
				}
				if (value === 'CompanyName') {
					// 获取公司下拉列表数据
					this.getCompanyDataList()
				} else {
					console.log('打开部门弹窗了', this.entity, )
					if (this.entity.CompanyId) {
						// 获取部门下拉列表
						this.getDepartmentList(this.entity.CompanyId)
					}
				}


			},

			//获取公司列表数据
			getCompanyDataList() {
				CompanyDataList({}).then(resJson => {
					if (resJson.Success) {
						this.columns = resJson.Data.map(item => {
							return {
								value: item.Id,
								label: item.title
							}
						})

					}
					this.$refs.Company.open(this.columns)
					console.log('获取公司列表数据', this.columns)
				})
			},

			// 审批意见 同意  -不同意
			dialogInputHandleSubmit(type, msg) {
				console.log('msg', msg)
				// if (!this.comment) return this.$errorToast('请输入审批意见')
				var that = this
				this.loading = true
				uni.showLoading({
					title: msg
				})
				// 工资审批提交
				Ai_WorkitemSalaryApproved({
					id: this.ApprovalFormId,
					comment: this.comment,
					flag: type
				}).then(resJson => {
					if (resJson.Success) {
						this.$sucessToast(msg === '提交中' ? '提交成功' : '审批成功')
						setTimeout(function() {
							that.loading = false
							uni.navigateBack()
							uni.hideLoading()
						}, 2500)

					} else {
						this.$errorToast(resJson.Msg)
						setTimeout(function() {
							that.loading = false
							uni.navigateBack()
							uni.hideLoading()
						}, 2500)
					}

				})
				// 关闭 弹窗
				this.$refs.inputDialog.close()
			},

			// 提交
			onSubmit(type) {
				// 如果点击的是审批按钮
				if (type == 2) {
					this.$refs.inputDialog.open()
					return
				}
				var that = this
				this.$refs.form.validate().then(res => {
					// this.resetFields()
					this.loading = true
					let newEntity = JSON.parse(JSON.stringify(this.entity))
					delete newEntity.CompanyName
					newEntity['TemplateId'] = this.options.TemplateId

					console.log('提交中---', newEntity)
					if (this.title === '新增') {
						uni.showLoading({
							title: '提交中'
						})
						Salary_PayrollWageApprovalProcess(newEntity)
							.then(resJson => {
								if (resJson.Success) {
									that.$sucessToast('提交成功')
									setTimeout(function() {
										that.loading = false
										uni.navigateBack()
										uni.hideLoading()

									}, 2500)
								} else {
									that.$errorToast(resJson.Msg);
									setTimeout(function() {
										that.loading = false
										uni.navigateBack()
										uni.hideLoading()
									}, 2500)
								}
							});
					} else {
						console.log('详情提交了')
						// 审批意见 同意  -不同意  重新提交直接默认值赋值
						this.dialogInputHandleSubmit(true, '提交中')
					}




				}).catch(err => {
					uni.hideLoading()
					that.loading = false
				})
			}

		}
	}
</script>

<style lang="less" scoped>
	.container {
		.scrollBox {

			margin-bottom: 130rpx;
			/* #ifdef H5 */
			height: calc(100vh - 360px);
			/* #endif */
			/* #ifdef APP */
			height: calc(100vh - 220px);
			/* #endif */
		}

		/* 适配底部导航栏 */
		.submitButton {
			background-color: #fff;
			position: fixed;

			padding-right: 20rpx;
			padding-left: 20rpx;
			padding-bottom: calc(constant(safe-area-inset-bottom) + 40rpx);
			padding-bottom: calc(env(safe-area-inset-bottom) + 40rpx);
			bottom: 0;
			width: 100%;

			button {
				height: 80rpx;
				border-radius: 10urpx;
				line-height: 80rpx;
				font-size: 28rpx;
				color: #FFFFFF;
				font-weight: bold;
			}
		}


		// .submitButton {
		// 	position: fixed;
		// 	left: 0;
		// 	right: 0;
		// 	bottom: 0;
		// 	height: 150rpx;
		// 	/*暂时发现安卓小屏手机安全区为0 && 不带单位的话padding-bottom会失效，写一个兜底, 并写在最上面；f12发现css样式如果都给height设置样式，会依次往下，用最底下的一个样式，如果最下面的没失效，依次往上查找，所以兜底的写在最上面 */
		// 	height: calc(150rpx + constant(safe-area-inset-bottom));
		// 	/* 直接扩展高度，因为padding-bottom是内边距 */
		// 	height: calc(150rpx + env(safe-area-inset-bottom));
		// 	/* 直接扩展高度 */
		// 	background: #fff;
		// 	box-sizing: border-box;
		// 	padding-bottom: constant(safe-area-inset-bottom);
		// 	/*兼容 iOS<11.2 */
		// 	padding-bottom: env(safe-area-inset-bottom);
		// 	/* 兼容iOS>= 11.2*/
		// 	border-top: 1px solid #e9e9e9;
		// 	padding-left: 15px;
		// 	padding-right: 15px;
		// }
	}
</style>